using B.S.BaseData.Api.Read.Command.Hosp;
using B.S.BaseData.Api.Read.Command.HospitalCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.AI;
using B.S.BataBase.Domain.DTO;
using B.S.BataBase.Domain.Hosp;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BaseData.Api.Read.CommandHandler.Hosp
{
    public class DepartmentShowCommandHandler : IRequestHandler<DepartmentShowCommand, APIResult<ApiPaging<Department>>>
    {
        private readonly IBaseRepository<Department> _repository;

        public DepartmentShowCommandHandler(IBaseRepository<Department> repository)
        {
            _repository = repository;
        }

        public async Task<APIResult<ApiPaging<Department>>> Handle(DepartmentShowCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<ApiPaging<Department>>();

            try
            {
                var res = _repository.GetAll().Where(x => !x.IsDeleted);
                if(request.HospitalId!=null)
                {
                    res = res.Where(x=>x.ParentDepartmentId == request.HospitalId);
                }
                var totaCount = res.Count();
                var pageCount = (int)Math.Ceiling(totaCount * 1.0 / request.pageSize);
                ApiPaging<Department> paging = new ApiPaging<Department>();
                paging.TotalPage = pageCount;
                paging.Total = totaCount;
                paging.PageData = res.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Data = paging;
                result.Code = ApiEnum.Success;
                result.Msg = "科室查询成功";
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = $"查询科室失败：{ex.Message}";
            }

            return result;
        }
    }
} 